package com.leyou.auth.interceptors;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.auth.utils.UserContext;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.CookieUtils;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 虎哥
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    private JwtUtils jwtUtils;

    public LoginInterceptor(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            // 1.从cookie中获取jwt
            String jwt = CookieUtils.getCookieValue(request, JwtConstants.COOKIE_NAME);
            // 2.验证并解析jwt
            Payload payload = jwtUtils.parseJwt(jwt);
            // 3.获取用户
            UserDetails userDetail = payload.getUserDetail();
            // 4.已登录，放行
            log.info("用户{}正在访问{}。", userDetail.getUsername(), request.getRequestURI());
            // 5.存储用户
            UserContext.setUser(userDetail);
            UserContext.setJwt(jwt);
            return true;
        } catch (JwtException e) {
            // 5.JWT有误或者已经过期
            throw new LyException(401, "JWT有误或者已经过期！");
        } catch (IllegalArgumentException e){
            // 5.JWT为空，未登录
            throw new LyException(401, "用户未登录！");
        } catch (RuntimeException e){
            throw new LyException(401, e.getMessage());
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 清空上下文中的数据
        UserContext.removeUser();
        UserContext.removeJwt();
    }
}
